package com.aiwu.memory;

import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.aiwu.bean.MemoryBean;
import com.aiwu.library.App;
import com.aiwu.library.abs.ui.adapter.BaseMultiFocusAdapter;
import com.aiwu.library.ui.widget.layoutmanager.MaxLinesFocusFixedLinearLayoutManager;
import com.aiwu.library.util.DisplayUtil;
import com.aiwu.library.util.DrawableUtil;
import com.aiwu.library.util.ToastUtil;
import com.aiwu.widget.TouchLinearLayout;
import com.chad.library.adapter.base.BaseViewHolder;

import org.citra.citra_emu.NativeLibrary;
import org.citra.citra_emu.R;

import java.util.List;

/**
 * 搜索结果列表
 */
public class MemoryResultListFragment extends BaseLazyFragment implements View.OnClickListener, MemoryManager.KeyBoardOffsetCallback, MemoryManager.OnActionCallback {
    private TextView tvTip;
    private EditText etNum;
    private CheckBox cbSelectAll;
    private RecyclerView rv;
    private final MemoryAdapter memoryAdapter = new MemoryAdapter();

    @Override
    protected void lazyLoad() {
        List<MemoryBean> memoryList = MemoryManager.getInstance().getMemoryList();
        int resultSize = memoryList.size();
        if (resultSize > 0 && resultSize <= MemoryManager.RESULT_NUM_THRESHOLD) {
            notifyTip(resultSize);
            for (MemoryBean item : memoryList) {
                long address = item.getAddress();
                long value = MemoryManager.GetUnsigned(NativeLibrary.readMemory(MemoryManager.GetSigned(address), 0));
                item.setValue(value);
            }
            notifyData(memoryList);
        }
        etNum.requestFocus();
    }

    @Override
    protected Boolean repeatedLoad() {
        return true;
    }

    @Override
    protected int initContentView() {
        return R.layout.fragment_memory_result_list;
    }

    @Override
    protected void initView(View view) {
        tvTip = view.findViewById(R.id.tv_tip);
        view.findViewById(R.id.tv_modify).setOnClickListener(this);
        view.findViewById(R.id.tv_create_cheat).setOnClickListener(this);
        view.findViewById(R.id.tv_continue_search).setOnClickListener(this);
        etNum = view.findViewById(R.id.et_num);
        MemoryManager.disableShowInput(etNum, false, this);
        cbSelectAll = view.findViewById(R.id.cb_select_all);
        cbSelectAll.setCompoundDrawables(DrawableUtil.getDrawableDimenRes(R.drawable.emu_lib_selector_cb_rec, R.dimen.qb_px_21), null, null, null);
        cbSelectAll.setOnClickListener(this);
        rv = view.findViewById(R.id.rv);
        rv.setItemAnimator(null);
        rv.setLayoutManager(new MaxLinesFocusFixedLinearLayoutManager(getContext())
                .setMaxLines(DisplayUtil.isPortrait() ? 5 : 2));
        rv.setAdapter(memoryAdapter);
        memoryAdapter.setOnItemChildClickListener((adapter, view1, position) -> {
            if (view1.getId() == R.id.iv_delete) {
                memoryAdapter.remove(position);
                int count = memoryAdapter.getItemCount();
                if (count <= 0) {
                    MemoryManager.getInstance().reset();
                    return;
                }
                notifyTip(count);
                notifyCbSelectAll();
            } else if (view1.getId() == R.id.iv_lock) {
                MemoryBean memoryBean = memoryAdapter.getItem(position);
                if (memoryBean != null) {
                    boolean newState = !memoryBean.isLocking();
                    memoryBean.setLocking(newState);
                    if (newState) {
                        MemoryManager.getInstance().addLockMemory(memoryBean);
                    } else {
                        MemoryManager.getInstance().removeLockMemory(memoryBean);
                    }
                }
                memoryAdapter.notifyItemChanged(position);
            } else if (view1.getId() == R.id.cb_selected) {
                MemoryBean memoryBean = memoryAdapter.getItem(position);
                if (memoryBean != null) {
                    memoryBean.setSelected(!memoryBean.isSelected());
                    notifyCbSelectAll();
                }
            }
        });
        MemoryManager.getInstance().addOnActionCallback(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MemoryManager.getInstance().removeOnActionCallback(this);
    }

    private void notifyData(List<MemoryBean> memoryList) {
        memoryAdapter.setNewData(memoryList);
        notifyCbSelectAll();
    }

    /**
     * 刷新提示文本
     */
    private void notifyTip(int size) {
        String endStr = " 个数值，把他们修改为?";
        String tipStr = "共搜索到 " + size + endStr;
        SpannableString ssTip = new SpannableString(tipStr);
        int start2 = 4;
        int end2 = tipStr.indexOf(endStr);
        ssTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.getContext(), R.color.text_imp)), start2, end2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssTip.setSpan(new StyleSpan(Typeface.BOLD), start2, end2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvTip.setText(ssTip);
    }

    /**
     * 刷新全选按钮
     */
    private void notifyCbSelectAll() {
        boolean isSelectAll = true;
        for (MemoryBean item : memoryAdapter.getData()) {
            if (!item.isSelected()) {
                isSelectAll = false;
                break;
            }
        }
        cbSelectAll.setChecked(isSelectAll);
    }

    /**
     * 全选/全不选
     */
    @SuppressLint("NotifyDataSetChanged")
    private void selectAll(boolean select) {
        for (MemoryBean item : memoryAdapter.getData()) {
            item.setSelected(select);
        }
        memoryAdapter.notifyDataSetChanged();
    }

    private void modifyMemory() {
        String strValue = etNum.getText().toString();
        if (TextUtils.isEmpty(strValue)) {
            ToastUtil.toast("请输入修改的值");
            return;
        }
        if (MemoryManager.isValueValid(strValue)) {
            MemoryManager.getInstance().modifyMemory(strValue);
        } else {
            ToastUtil.toast("输入的值有误，请重新输入");
            etNum.setText("");
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_continue_search) {
            MemoryManager.getInstance().backGame();
        } else if (v.getId() == R.id.tv_modify) {
            modifyMemory();
        } else if (v.getId() == R.id.tv_create_cheat) {
            MemoryManager.getInstance().createCheat();
        } else if (v.getId() == R.id.cb_select_all) {
            selectAll(cbSelectAll.isChecked());
        }
    }

    @Override
    public boolean setKeyBoardOffset(ViewGroup.MarginLayoutParams layoutParams) {
        if (DisplayUtil.isPortrait()) {
            View view = getView().findViewById(R.id.layout_content);
            if (view != null) {
                int marginH = getResources().getDimensionPixelOffset(R.dimen.qb_px_45);
                layoutParams.setMargins(marginH, view.getTop(), marginH, 0);
                return true;
            }
        }
        return false;
    }

    @Override
    public void onShowKeyboard() {
        ViewGroup viewGroup = getView().findViewById(R.id.layout_content);
        if (viewGroup instanceof TouchLinearLayout) {
            viewGroup.setForeground(new ColorDrawable(getResources().getColor(R.color.black_50)));
            ((TouchLinearLayout) viewGroup).setInterceptTouch(true);
        }
    }

    @Override
    public void onCloseKeyboard() {
        View viewGroup = getView().findViewById(R.id.layout_content);
        if (viewGroup instanceof TouchLinearLayout) {
            viewGroup.setForeground(null);
            ((TouchLinearLayout) viewGroup).setInterceptTouch(false);
        }
    }

    private static class MemoryAdapter extends BaseMultiFocusAdapter<MemoryBean, BaseViewHolder> {

        public MemoryAdapter() {
            super(R.layout.item_memory, null);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, MemoryBean item) {
            CheckBox cbSelected = helper.getView(R.id.cb_selected);
            cbSelected.setCompoundDrawables(DrawableUtil.getDrawableDimenRes(R.drawable.emu_lib_selector_cb_rec, R.dimen.qb_px_21), null, null, null);
            cbSelected.setChecked(item.isSelected());
            cbSelected.setText(item.getAddressStr() + ":" + item.getValueStr());
            helper.setImageResource(R.id.iv_lock, item.isLocking() ? R.drawable.ic_memory_locked : R.drawable.ic_memory_unlock)
                    .addOnClickListener(R.id.iv_lock, R.id.iv_delete, R.id.cb_selected);
        }
    }
}
